#include <memory>
#include <iostream>
using std::cout;
using std::endl;
using std::shared_ptr;
using std::weak_ptr;

class Point
{
public:
    Point(int ix = 0, int iy = 0)
    : _ix(ix)
    , _iy(iy)
    {   cout << "Point(int,int)" << endl;    }

    ~Point()
    {   cout << "~Point()" << endl; }  

    void print() const 
    {
        cout << "(" << _ix
             << "," << _iy
             << ")" << endl;
    }

private:
    int _ix;
    int _iy;
};

void test0()
{
    weak_ptr<Point> wp;
    {
        shared_ptr<Point> sp(new Point(10, 12));
        wp = sp;//对weak_ptr进行赋值操作,不会导致引用计数加1

        cout << "sp's use_count:" << sp.use_count() << endl;
        cout << "wp's use_count:" << wp.use_count() << endl;
        cout << "所托管的对象是否超时:" << wp.expired() << endl;

        //wp->print();//errror  weak_ptr不能访问资源
        //对weak_ptr进行提升之后，才能访问资源
        shared_ptr<Point> sp2 = wp.lock();
        if(sp2) {
            cout << "weak_ptr提升成功" << endl;
            sp2->print();
        } else {
            cout << "weak_ptr提升失败" << endl;
        }
    }//语句块
    
    cout << "所托管的对象是否超时:" << wp.expired() << endl;
    cout << "wp's use_count:" << wp.use_count() << endl;
    shared_ptr<Point> sp2 = wp.lock();
    if(sp2) {
        cout << "weak_ptr提升成功" << endl;
        sp2->print();
    } else {
        cout << "weak_ptr提升失败" << endl;
    }
}


int main()
{
    test0();
    return 0;
}

